package org.example.petitionplatformsystem.webRTC;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/websocket/{userId}") // websocket终端地址
@Component // 将该类交给spring管理
public class WebSocketServer {
    private final static Map<Long, Session> sessions = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Long userId) {
        System.out.println("生成sessions的用户:" + userId);
        sessions.put(userId, session);
    }

    @OnMessage
    public void onMessage(String msg, @PathParam("userId") Long userId) throws IOException {
        JSONObject jsonObject = new JSONObject(msg);
        String type = jsonObject.getString("type");
        Long roomId = jsonObject.getLong("roomId");
        System.out.println("-------------------------------------");
        System.out.println(type + " " + roomId);

        if (type.equals("joinRoom")) {
            if (roomId != 0L) { // 工作人员进来时
                joinStaffRoom(userId, roomId);
            } else { // 普通用户进来时
                roomId = findAndJoinAvailableRoom(userId);
            }
            // 将分配好的房间号传回前端
            JSONObject roomIdJson = new JSONObject();
            roomIdJson.put("type", "getRoomId");
            roomIdJson.put("roomId", String.valueOf(roomId));
            sendMessage(userId, roomIdJson.toString());
        } else {
            forwardMessageToRoom(msg, userId, roomId, type);
        }
    }

    @OnClose
    public void onClose(@PathParam("userId") Long userId) {
        System.out.println("删除sessions的用户：" + userId);
        sessions.remove(userId);
    }

    private void joinStaffRoom(Long userId, Long roomId) {
        CallingRoom callingRoom = StaticModel.getRoomByRoomId(roomId);
        if (callingRoom == null) {
            System.out.println("职员" + userId + "创建并加入房间" + roomId);
            callingRoom = new CallingRoom(roomId);
            StaticModel.roomList.add(callingRoom);
        } else {
            System.out.println("职员" + userId + "加入现有房间" + roomId);
        }
        callingRoom.getCallingUsersList().add(userId);
        System.out.println(roomId);
    }

    private Long findAndJoinAvailableRoom(Long userId) {
        Long assignedRoomId = 0L;
        for (CallingRoom room : StaticModel.roomList) {
            if (room.isFree()) {
                assignedRoomId = room.getRoomId();
                room.setFree(false);
                System.out.println("用户" + userId + "加入房间" + assignedRoomId);
                room.getCallingUsersList().add(userId);
                break;
            }
        }
        return assignedRoomId;
    }

    private void forwardMessageToRoom(String msg, Long userId, Long roomId, String type) {
        CallingRoom room = StaticModel.getRoomByRoomId(roomId);
        System.out.println("用户：" + userId + ",事件：" + type + ",房间：" + roomId);
        if (room != null) {
            for (Long id : room.getCallingUsersList()) {
                sendMessage(id, msg);
            }
        }
    }

    private void sendMessage(Long userId, String msg) {
        try {
            sessions.get(userId).getBasicRemote().sendText(msg);
        } catch (Exception e) {
            System.err.println("发送消息失败，用户ID: " + userId);
            e.printStackTrace();
        }
    }
}
